//
// Created by Deng on 2021/8/12.
// 成员函数中将this 指针交给全局变量

#include <iostream>
#include <thread>
using namespace std;
int volatile run = true;

/**
 * 基类
 */
class BaseFrame{
public:
    virtual void  Show() = 0;
    virtual void printSomething() = 0;
    virtual ~BaseFrame(){
        cout << "~BaseFrame"<< endl;
    };
};
//全局变量
BaseFrame* frame = nullptr;

/**
 * 子线程中运行
 */
void frameRun(){
    while (run){
        frame->printSomething();
    }
}
/**
 * 子类
 */
class Frame : BaseFrame{
private:
public:

    void Show()override {
        frame = this;
        //交给子线程
        std::thread t(frameRun); //detach方式，启动的线程自主在后台运行，当前的代码继续往下执行，不等待新线程结束
        t.detach();
    }
    void printSomething()override {
        cout << "this is Frame printSomething" << endl;
    }
    ~Frame()override {
        cout << "~Frame" << endl;
    }
};

class App{
private:
    int i = 0;
public:
    bool OnInit(){
        auto  f = new Frame();
        i = 2;
        f->Show();
        return true;
    }
};

int main_demo(){
    App app;
    bool b = app.OnInit();
    int i = 2;
    while (b && i > 0){
        std::this_thread::sleep_for(std::chrono::seconds(1));
        i--;
    }
    run = false;
    delete frame;
}